import { Form, Input, Button, Checkbox ,Card , message} from 'antd'
import {useDispatch} from 'react-redux'
import logo from '../../assets/logo.png'
import styles from './index.module.scss'
import {login} from '../../store/actions/login.js'
import { useState } from 'react'

const Login = ({history}) => {
    const dispatch = useDispatch()
    const [loading,setLoading] = useState(false)
    const onFinish = async (values) => {
      try {
        setLoading(true)
        await dispatch(login(values))
        message.success('登录成功',1.5,()=>{
          // console.log(history);
          let path = '/home'
          history.location.state&&(path = history.location.state.from )
          history.replace(path)
        })
      } catch (error) {
        const mag = error.response.data.message || '登录失败'
        message.error(mag)
      } finally{
        setLoading(false)
      } 
    }    
    const onFinishFailed = (errorInfo) => {
      console.log('Failed:', errorInfo);
    }
  return (
    <div className={styles.root}>
      <Card className="login-container">
        <img className="login-logo" src={logo} alt="" />
        {/* 登录表单 */}
        <Form
      name="basic"
      wrapperCol={{
        offset: 2,
        span: 20
      }}
      initialValues={{
        remember: true,
        code:'246810',
        mobile:'13911111111'
      }}
      onFinish={onFinish}
      onFinishFailed={onFinishFailed}
      autoComplete="off"
    >
      <Form.Item
        name="mobile"
        validateTrigger='onBlur'
        rules={[
          {
            required: true,
            message: '请输入手机号!',
          },
          {
            pattern: /^1[3-9]\d{9}$/,
            message: '手机号码格式不对'
          },
        ]}
      >
        <Input
        size="large" 
        placeholder="请输入手机号" />
      </Form.Item>

      <Form.Item
        validateTrigger= 'onBlur'
        name="code"
        rules={[
          {
            required: true,
            message: '请输入验证码!',
          },
        //   { len: 6, message: '验证码6个字符', }
        ]}
      >
        <Input.Password 
        size="large" 
        placeholder="请输入验证码"
        maxLength={6}/>
      </Form.Item>

      <Form.Item
        name="remember"
        valuePropName="checked"
        rules={[
            {
              validator (rule, value) {
                if (value) {
                  return Promise.resolve()
                } else {
                  return Promise.reject(new Error('请阅读并同意协议'))
                }
              }
            }
          ]}>
        <Checkbox>我已阅读并同意[隐私条款]</Checkbox>
      </Form.Item>

      <Form.Item
      >
        <Button size="large" block type="primary" htmlType="submit" loading={loading}>
          提交
        </Button>
      </Form.Item>
    </Form>
      </Card>
    </div>
  )
}

export default Login
